<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>更改密码</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
<h1>更改密码</h1>
<form id="changePasswordForm">
    <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required>
    </div>
    <div>
        <label for="oldPassword">旧密码:</label>
        <input type="password" id="oldPassword" name="oldPassword" required>
    </div>
    <div>
        <label for="newPassword">新密码:</label>
        <input type="password" id="newPassword" name="newPassword" required>
    </div>
    <div>
        <button type="submit">更改密码</button>
    </div>
    <div id="errorMessage" class="error"></div>
</form>

<script>
    $(document).ready(function() {
        $('#changePasswordForm').on('submit', function(event) {
            event.preventDefault();

            const username = $('#username').val();
            const oldPassword = $('#oldPassword').val();
            const newPassword = $('#newPassword').val();

            $.ajax({
                url: '/users/changePassword',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ username, oldPassword, newPassword }),
                success: function(response) {
                    alert('密码更改成功');
                    // 重定向到登录页面
                    window.location.href = '/login';
                },
                error: function(xhr, status, error) {
                    const errorMessage = xhr.responseJSON ? xhr.responseJSON.message : '未知错误';
                    $('#errorMessage').text(errorMessage);
                }
            });
        });
    });
</script>
</body>
</html>
